#include "GpsSensor.h"
#include "CommandExecutor.h"
#include "CommandDispatcher.h"

GpsSensor::GpsSensor(DummyChannel& channel, const ExtendDeviceType& deviceType, const std::string& deviceActknowlege): ExtendDevice(channel, deviceType, deviceActknowlege), mcommandExecutor(CommandExecutorSingleton::instance()) {

}


bool GpsSensor::activeUpdateInformation(void) {
    bool recheckResult = false;
    std::string result;
    try {
        mchannel.sendStringReturnString(std::string("<GET_GPS>"), result);
        recheckResult = true;
        if ("<GET_GPS_ERROR>" == result) {
            recheckResult = true;
        } else {
            StringVector fieldStrings;
            fieldStrings.reserve(20);
            //result.erase(0, 9);
            StringUtility::split(result.substr(9, result.size() - 10), ",", fieldStrings);
//            if ("N" == fieldStrings[11]){
//                return recheckResult;
//            }

            latitude = fieldStrings[2];
            if (!fieldStrings[3].empty())
                latitudeSymbol = fieldStrings[3][0];

            longitude = fieldStrings[4];
            if (!fieldStrings[5].empty())
                longitudeSymbol = fieldStrings[5][0];

            satelliteQuantity = fieldStrings[12];
            signalNoise = fieldStrings[13];

            std::string dateString = fieldStrings[9] + fieldStrings[0];
            if (!dateString.empty() && ConnectionStatus::ONLINE != CommandDispatcherSingleton::instance().getConnectionStatus()) {
                std::string format = "%d%m%YY%H%M%S";//ddMMyyHHmmss

                std::tm nowTm;
                std::memset(&nowTm, 0, sizeof (nowTm));
                std::string::value_type* pEnd = ::strptime(dateString.data(), format.data(), &nowTm);
                if (pEnd) {
                    std::time_t utcTime = std::mktime(&nowTm);
                    utcTime += 8 * 3600;
                    ::gmtime_r(&utcTime, &nowTm);
                    mcommandExecutor.setSystemTime(nowTm);
                }
            }
        }
    } catch (std::exception& ex) {
        LOG_ERROR(ex.what());
    }
    return recheckResult;

}

bool GpsSensor::updateInformation(void) {

    return true;
}


